<template>
	<div class="login-container">
		<el-alert :title="lan.welcome" type="success" :closable="false" style="position: fixed"></el-alert>
		<el-row>
			<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
				<div style="text-align: right;width: 98%;padding-top: 5px;">
					<language></language>
				</div>
			</el-col>
			<el-col :xs="24" :sm="24" :md="12" :lg="16" :xl="16">
				<div style="color: transparent">{{ projectName }}</div>
			</el-col>

			<el-col v-if="isLogin" :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
				<el-form ref="model" :model="model" :rules="rules" class="login-form" label-position="left"
					:inline="false">
					<!-- <div class="title">{{lan.hello}}</div>
                    <div class="title-tips">{{stringFormat(lan.welcomeFull,comLan.shortName)}}</div> -->
					<div class="title">{{comLan.projectName}}</div>
					<el-form-item style="margin-top: 40px" prop="uid">
						<span class="svg-container svg-container-admin">
							<vab-remix-icon icon="user-line" />
						</span>
						<el-input v-model.trim="model.uid" v-focus :placeholder="lan.uid" tabindex="1" type="text"
							@keyup.enter.native="handleLogin" />
					</el-form-item>
					<el-form-item prop="pwd">
						<span class="svg-container">
							<vab-remix-icon icon="lock-password-line" />
						</span>
						<el-input :key="passwordType" ref="pwd" v-model.trim="model.pwd" :type="passwordType"
							tabindex="2" :placeholder="lan.pwd" @keyup.enter.native="handleLogin" />
						<span v-if="passwordType === 'password'" class="show-password" @click="handlePassword">
							<vab-remix-icon icon="eye-off-fill" />
						</span>
						<span v-else class="show-password" @click="handlePassword">
							<vab-remix-icon icon="eye-fill" />
						</span>
					</el-form-item>
					<el-form-item v-if="webConfig.NeedCaptcha" prop="captchaText">
						<span class="svg-container">
							<vab-remix-icon icon="barcode-line" />
						</span>
						<el-input v-model.trim="model.captchaText" :placeholder="lan.captchaText" tabindex="3"
							type="text" @keyup.enter.native="handleLogin" />
						<div class="admin-captcha-img pointer" @click="createCaptcha">
							<vab-remix-icon v-if="captchaLoading" icon="loader-2-line" />
							<img v-else :src="captchaBase64" width="100%" height="100%"></img>
						</div>
					</el-form-item>

					<div class="verify-container" v-if="loading&&loginWithPicValidate">
						<vab-verify ref="slideDiv" :w="350" :slider-text="lan.slideRight" :h="175"
							@success="handleSuccess" @fail="handleError">
						</vab-verify>
					</div>

					<el-button id="btnLogin" :loading="loading" class="login-btn" type="primary" @click="handleLogin">
						{{lan.btnLogin}}
					</el-button>
					<div class="login-btn" style="height:60px;width:60px;padding-top: 20px;" v-if="showWechatQr">
						<a href="javascript:;"><img src="/static/img/wechat.png" style="height:60px;width:60px"
								@click="wechatQr" /></a>
					</div>
					<el-button v-if="false" id="btnLogin2" :loading="loading" class="login-btn" type="primary"
						@click="handleLogin2">
						登录2(类传值)
					</el-button>

					<a @click="isLogin=false" v-if="false">
						<div style="margin-top: 20px">{{lan.btnRegister}}</div>
					</a>
				</el-form>
			</el-col>

			<el-col v-else :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
				<el-form ref="registerForm" :model="model" class="register-form" :rules="registerRules" size="mini"
					:inline="false">
					<el-form-item prop="uid">
						<span class="svg-container2  svg-container-admin2">
							<vab-remix-icon icon="user-line" />
						</span>
						<el-input v-model.trim="model.uid" v-focus style="margin-top: 20px" type="text"
							:placeholder="lan.uid" auto-complete="off">
						</el-input>
					</el-form-item>
					<el-form-item prop="phone">
						<span class="svg-container2">
							<vab-remix-icon icon="cellphone-fill" />
						</span>
						<el-input v-model.trim="model.phone" type="text" :placeholder="lan.phone" maxlength="11"
							show-word-limit autocomplete="off">
						</el-input>
					</el-form-item>
					<el-form-item prop="phoneCode">
						<span class="svg-container2">
							<vab-remix-icon icon="message-2-line" />
						</span>
						<el-input v-model.trim="model.phoneCode" type="text" :placeholder="lan.phoneCode">
						</el-input>
						<el-button type="primary" class="show-pwd phone-code" :disabled="isGetphone"
							@click="getPhoneCode">
							{{lan.getPhoneCode}}
						</el-button>
					</el-form-item>
					<el-form-item prop="pwd">
						<span class="svg-container2">
							<vab-remix-icon icon="lock-password-line" />
						</span>
						<el-input v-model.trim="model.pwd" type="pwd" :placeholder="lan.setPwd"
							autocomplete="new-password">
						</el-input>
					</el-form-item>
					<el-form-item>
						<el-button class="register-btn" type="primary" @click.native.prevent="handleReister">
							{{lan.btnRegister}}
						</el-button>
						<a @click="isLogin = true">
							<div style="margin-top: 20px">{{lan.btnLogin}}</div>
						</a>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>

		<!--选择门店-->
		<el-dialog width="60%" :title="lan.dialog" :visible.sync="dialogvisible" @close="loginSuccess">
			<el-select v-model="selected" style="width:100%">
				<el-option v-for="item in listLoginInfo" :key="item.Token" :value="item.Token"
					:label="showLoginHtml(item,false)">
					<span v-html="showLoginHtml(item,true)"></span>
				</el-option>
			</el-select>
			<br />
			<div slot="footer" class="dialog-footer">
				<el-button @click="loginSuccess">{{lan.btnLogin}}</el-button>
			</div>
		</el-dialog>

		<!--微信扫码登录-->
		<el-dialog width="500px" :title="lan.qrScanTitle" :visible.sync="visible">
			<div id="wechatQrLoginDivId" style="margin: 0 auto;text-align: center;"></div>
		</el-dialog>
	</div>
</template>

<script>
	import common from "@/common/common.js";
	import config from "@/common/config.js";
	import language from "@/common/language/language.vue"

	export default {
		mixins: [common.baseVM],
		components: {
			language
		},
		computed: {
			projectName: function() {
				return this.$store.state.projectName;
			},
			loginWithPicValidate: function() {
				return config.loginWithPicValidate;
			},
			showLanguage() {
				return config.showLanguage
			},

			showWechatQr() {
				if (this.isWechat) return false;
				if (!!this.webConfig.WebAppID) return true;
				return false;
			}
		},
		directives: {
			focus: {
				inserted(el) {
					el.querySelector("input").focus();
				},
			},
		},
		data() {
			return {
				isLogin: true, //true登录,false注册
				model: {
					uid: "",
					pwd: "",
					captchaText: ""
				},
				IsYes: [{
					Value: false,
					Label: '否',
					Color: 'red'
				}, {
					Value: true,
					Label: '是',
					Color: 'blue'
				}],

				captchaLoading: false,
				webConfig: {
					NeedCaptcha: false, //是否需要验证码
					WebAppID: "" //扫码登录的网站应用appid
				},

				captchaBase64: '',

				rules: {
					uid: [{
						required: true,
						trigger: "blur",
						validator: (rule, value, callback) => {
							if (value == null || value == "") {
								callback(new Error(this.lan.uidVali));
							} else {
								callback();
							}
						}
					}],
					pwd: [{
						required: true,
						trigger: "blur",
						validator: (rule, value, callback) => {
							if (value == null || value.length < 6) {
								callback(new Error(this.lan.pwdVali));
							} else {
								callback();
							}
						}
					}],
					//验证码
					captchaText: [{
						required: true,
						trigger: "blur",
						validator: (rule, value, callback) => {
							if (value == null || value.length < 1) {
								callback(new Error(this.lan.captchaText));
							} else {
								callback();
							}
						}
					}]
				},
				loading: false,
				passwordType: "password",
				redirect: undefined,

				isGetphone: false,
				getPhoneIntval: null,
				registerRules: {
					uid: [{
						required: true,
						trigger: "blur",
						validator: (rule, value, callback) => {
							if ("" == value) {
								callback(new Error(this.lan.uidVali));
								return;
							}
							if (value.length > 20) {
								callback(new Error(this.lan.uidMaxVali));
								return;
							}
							callback();
						}
					}],
					phone: [{
						required: true,
						trigger: "blur",
						validator: (rule, value, callback) => {
							if (!common.tool.isPhone(value)) {
								callback(new Error(this.lan.phoneVali));
								return;
							}
							callback();
						}
					}],
					pwd: [{
						required: true,
						trigger: "blur",
						validator: (rule, value, callback) => {
							if (value == null || value.length < 6) {
								callback(new Error(this.lan.pwdVali));
								return;
							}
							callback();
						}
					}],
					phoneCode: [{
						required: true,
						trigger: "blur",
						validator: (rule, value, callback) => {
							if (value == null || value.length < 6) {
								callback(new Error(this.lan.phoneCodeVali));
								return;
							}
							callback();
						}
					}]
				},
				dialogvisible: false,
				listLoginInfo: [],
				selected: null
			};
		},
		watch: {
			$route: {
				handler(route) {
					this.redirect = (route.query && route.query.redirect) || "";
					if (this.isWechat) return; //微信浏览器,就不执行下面的代码了
					var code = this.queryString("code");
					//console.log("code", code);
					if (!!code) {
						var postData = this.toKeyValue({
							code: code
						});
						this.post('/api/Login/GetWebOpenID', postData).then((data) => {
							if (data.Success) {
								common.loginSuccess(data);
								if (data.Result == null || data.Result.length == 0) {
									this.showToast("登录帐号即可绑定微信", "success");
									this.visible = false;
									return;
								}
								return;
							} else {
								this.showMsg('获取openid失败,请刷新重试');
								return;
							}
						});
						return;
					}
				},
				immediate: true
			}
		},
		created() {
			document.body.style.overflow = "hidden";

			// this.model.uid = "";
			// this.model.pwd = "";
			//this.md5("123456");

			this.getNeedCaptcha();
		},
		beforeDestroy() {
			document.body.style.overflow = "auto";

			this.getPhoneIntval = null;
			clearInterval(this.getPhoneIntval);
			//console.log("login beforeDestroy");
		},
		mounted() {},
		methods: {
			wechatQr() {
				this.visible = true;
				this.$nextTick(() => {
					var locationHref = encodeURIComponent(window.location.href);
					var obj = new WxLogin({
						self_redirect: false,
						id: "wechatQrLoginDivId",
						appid: this.webConfig.WebAppID,
						scope: "snsapi_login",
						redirect_uri: locationHref,
						state: "State",
						style: "",
						href: ""
					});
				});
			},

			queryString(val) {
				var url = window.location.href;
				if (url.indexOf('?') == -1) return "";
				var reg = new RegExp("(^|&)" + val + "=([^&]*)(&|$)", "i");
				var r = url.split('?')[1].match(reg);
				if (r != null) return decodeURIComponent(r[2]);
				return null;
			},

			showLoginHtml(item, showHtml) {
				var html = showHtml ?
					this.getLabel(item.IsMainStore, this.IsYes) :
					this.getLabel(item.IsMainStore, this.IsYes, "", "", false);
				var r =
					`${this.comLan["belongStore"]}:${item.SysStoreName};${this.comLan["isMainStore"]}:${html};${this.comLan["loginUid"]}:${item.UserCode};${this.comLan["employeeName"]}:${item.UserName}`;
				return r;
			},

			getPhoneCode() {
				if (!common.tool.isPhone(this.model.phone)) {
					this.$refs["registerForm"].validateField("phone");
					return;
				}
				this.isGetphone = true;
				let n = 60;
				this.getPhoneIntval = setInterval(() => {
					if (n > 0) {
						n--;
						this.phoneCode = this.lan.retryGet + "(" + n + "s)";
					} else {
						this.getPhoneIntval = null;
						clearInterval(this.getPhoneIntval);
						this.phoneCode = this.lan.getPhoneCode;
						this.isGetphone = false;
					}
				}, 1000);
			},
			handleReister() {
				this.$refs["registerForm"].validate(async (valid) => {
					if (valid) {
						this.showToast("注册成功", "success");
					}
				});
			},
			md5: function() {
				var result = common.tool.md5("123456");
				console.log(result, result.toUpperCase());
			},

			handlePassword() {
				this.passwordType === "password" ?
					(this.passwordType = "") :
					(this.passwordType = "password");
				this.$nextTick(() => {
					this.$refs.pwd.focus();
				});
			},
			handleLogin(e) {
				this.formValidate("model", () => {
					this.loading = true;
					if (this.loginWithPicValidate == false) {
						this.handleSuccess();
					}
				});
			},
			handleLogin2(e) {
				this.formValidate("model", () => {
					this.loading = true;
					if (this.loginWithPicValidate == false) {
						var temp = common.showToast(this.lan.logining);
						var postData = {
							uid: this.model.uid,
							pwd: common.tool.md5(this.model.pwd),
							captchaText: this.model.captchaText
						};
						var redict = this.redict;
						this.post('/api/Login/Login2', postData).then((data) => {
							if (temp != null) temp.close();
							this.listLoginInfo = data.Result;
							if (this.listLoginInfo.length >= 1) {
								this.selected = this.listLoginInfo[0].Token;
							} else {
								this.showToast(this.lan.loginError);
								return;
							}
							if (this.listLoginInfo.length > 1) {
								this.dialogvisible = true;
							} else {
								this.loginSuccess();
							}
						}).catch((data) => {
							if (temp != null) temp.close();
							this.loading = false;
							this.createCaptcha();
						});
					}
				});
			},
			handleSuccess() {
				//this.testLogin();
				this.login();
			},
			login: function() {
				var temp = common.showToast(this.lan.logining);
				var postData = this.toKeyValue({
					uid: this.model.uid,
					pwd: common.tool.md5(this.model.pwd),
					captchaText: this.model.captchaText
				});
				var redict = this.redict;
				this.post('/api/Login/Login', postData).then((data) => {
					if (temp != null) temp.close();
					this.listLoginInfo = data.Result;
					if (this.listLoginInfo.length >= 1) {
						this.selected = this.listLoginInfo[0].Token;
					} else {
						this.showToast(this.lan.loginError);
						return;
					}
					if (this.listLoginInfo.length > 1) {
						this.dialogvisible = true;
					} else {
						this.loginSuccess();
					}
				}).catch((data) => {
					if (temp != null) temp.close();
					this.loading = false;
					this.createCaptcha();
				});
			},
			loginSuccess() {
				var info = null;
				for (var i = 0; i < this.listLoginInfo.length; i++) {
					var item = this.listLoginInfo[i];
					if (this.selected == item.Token) {
						info = item;
						break;
					}
				}
				if (info == null) info = this.listLoginInfo[0];
				var temp = common.showToast(this.lan.loginSuccess, "success");
				config.loginSetInfo(info);
				setTimeout(() => {
					if (temp != null) temp.close();
				}, 500);
			},

			//测试用的
			testLogin() {
				var temp = this.showToast(this.lan.logining);
				setTimeout(() => {
					if (temp != null) temp.close();
					temp = this.showToast(this.lan.loginSuccess, "success");
					if (!!this.redirect) {
						this.navigateTo(this.redirect);
						return;
					}
					var user = Object.assign(this.$store.state.user, {
						token: "123456",
						uid: "admin",
						userHeader: "",
					});
					user.userHeader = this.commonUrl(user.userHeader);
					this.$store.dispatch("setUser", user);
					this.$store.dispatch("setRoutes", config.testRoutes);

					this.navigateTo("/pages/index");
					setTimeout(() => {
						if (temp != null) temp.close();
					}, 500);
				}, 500);
			},
			handleError() {
				this.showToast(this.lan.verifyError, "error");
			},

			createCaptcha() {
				if (!this.webConfig.NeedCaptcha) return;
				this.captchaLoading = true
				this.post('/api/Login/CreateCaptcha').then(res => {
					this.captchaBase64 = res.Result;
				}).catch(err => {}).finally(err => {
					this.captchaLoading = false;
				});
			},

			getNeedCaptcha() {
				this.post('/api/Login/GetNeedCaptcha').then(res => {
					this.webConfig = res.Result;
					this.createCaptcha();
				}).catch(err => {}).finally(err => {})
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import "@/css/variables.scss";

	.login-container {
		height: 100vh;
		background: url("/static/img/login_images/background.jpg") center center fixed no-repeat;
		background-size: cover;

		.title {
			font-size: 54px;
			font-weight: 500;
			color: rgba(14, 18, 26, 1);
		}

		.title-tips {
			margin-top: 10px;
			font-size: 26px;
			font-weight: 400;
			color: rgba(14, 18, 26, 1);
			text-overflow: ellipsis;
			white-space: nowrap;
		}

		.login-btn,
		.register-btn {
			display: inherit;
			width: 220px;
			height: 60px;
			margin-top: 5px;
			border: 0;

			&:hover {
				opacity: 0.7;
			}
		}

		.login-form,
		.register-form {
			position: relative;
			max-width: 100%;
			margin: calc((100vh - 555px) / 2) 10% 10%;
			overflow: hidden;

			.forget-password {
				//width: 100%;
				margin-top: 40px;
				text-align: left;

				.forget-pass {
					width: 129px;
					height: 19px;
					font-size: 20px;
					font-weight: 400;
					color: rgba(92, 102, 240, 1);
				}
			}

			.per-code {
				width: 100px;
				height: 36px;
				font-size: 20px;
				line-height: 36px;
				color: #fff;
				text-align: center;
				cursor: pointer;
				background: #bbc1ce;
			}

			.phone-code {
				//width: 120px;
				position: absolute;
				top: 10px;
				right: 20px;
				height: 36px;
				font-size: 14px;
				color: #fff;
				border-radius: 3px;
				cursor: pointer;
				user-select: none;
			}
		}

		.tips {
			margin-bottom: 10px;
			font-size: $base-font-size-default;
			color: $base-color-white;

			span {
				&:first-of-type {
					margin-right: 16px;
				}
			}
		}

		.title-container {
			position: relative;

			.title {
				margin: 0 auto 40px auto;
				font-size: 34px;
				font-weight: bold;
				color: $base-color-blue;
				text-align: center;
			}
		}

		.svg-container {
			position: absolute;
			top: 9px;
			left: 15px;
			z-index: $base-z-index;
			font-size: 16px;
			color: #d7dee3;
			cursor: pointer;
			user-select: none;
		}

		.svg-container2 {
			position: absolute;
			top: 10px;
			left: 15px;
			z-index: $base-z-index;
			font-size: 16px;
			color: #d7dee3;
			cursor: pointer;
			user-select: none;
		}

		.svg-container-admin2 {
			top: 32px;
		}

		.show-password {
			position: absolute;
			top: 10px;
			right: 20px;
			font-size: 16px;
			color: #d7dee3;
			cursor: pointer;
			user-select: none;
		}

		::v-deep {
			.el-form-item {
				padding-right: 0;
				margin: 20px 0;
				color: #454545;
				background: transparent;
				border: 1px solid transparent;
				border-radius: 2px;

				&__content {
					min-height: $base-input-height;
					line-height: $base-input-height;
				}

				&__error {
					position: absolute;
					top: 100%;
					left: 18px;
					font-size: $base-font-size-small;
					line-height: 18px;
					color: $base-color-red;
				}
			}

			.el-input {
				box-sizing: border-box;

				.el-input__count {
					.el-input__count-inner {
						background: transparent;
					}
				}

				.el-input__prefix {
					left: 15px;
					line-height: 56px;

					.svg-inline--fa {
						width: 20px;
					}
				}

				input {
					height: 50px;
					padding-left: 45px;
					font-size: $base-font-size-default;
					line-height: 50px;
					color: $base-font-color;
					background: #f6f4fc;
					border: 0;
					caret-color: $base-font-color;
				}
			}
		}
	}

	.verify-container {
		// position: relative;
	}

	.admin-captcha-img {
		position: absolute;
		top: 1px;
		right: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #fff;
		width: 120px;
		height: 94%;
		border: 1px #E5E5E5 solid;
		border-radius: 0 5px 5px 0;
		background-color: #f9f9f9;
		z-index: 10;
	}
</style>
